package com.famiover.generator.generator;

import com.google.common.base.Preconditions;
import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType;

import java.util.List;
import java.util.Objects;

import static org.mybatis.generator.internal.util.messages.Messages.getString;

public class MybatisCodeGenerator {

    public static FullyQualifiedJavaType getFullyQualifiedJavaType(IntrospectedTable introspectedTable) {
        FullyQualifiedJavaType paramListType;
        if (introspectedTable.getRules().generateBaseRecordClass()) {
            paramListType = new FullyQualifiedJavaType(introspectedTable.getBaseRecordType());
        } else if (introspectedTable.getRules().generatePrimaryKeyClass()) {
            paramListType = new FullyQualifiedJavaType(introspectedTable.getPrimaryKeyType());
        } else {
            throw new RuntimeException(getString("RuntimeError.12")); //$NON-NLS-1$
        }
        return paramListType;
    }


    public static FullyQualifiedJavaType getFullyQualifiedExampleType(IntrospectedTable introspectedTable) {
        FullyQualifiedJavaType paramListType;
        if (introspectedTable.getRules().generateBaseRecordClass()) {
            paramListType = new FullyQualifiedJavaType(introspectedTable.getExampleType());
        } else if (introspectedTable.getRules().generatePrimaryKeyClass()) {
            paramListType = new FullyQualifiedJavaType(introspectedTable.getPrimaryKeyType());
        } else {
            throw new RuntimeException(getString("RuntimeError.12")); //$NON-NLS-1$
        }
        return paramListType;
    }

    public static String getPrimaryKeyShortName(IntrospectedTable introspectedTable) {
        return getPKFullyQualifiedJavaType(introspectedTable).getShortName();
    }

    public static FullyQualifiedJavaType getPrimaryKeyFullyQualifiedJavaType(IntrospectedTable introspectedTable) {
        return new FullyQualifiedJavaType(getPKFullyQualifiedJavaType(introspectedTable).getFullyQualifiedName());
    }


    private static FullyQualifiedJavaType getPKFullyQualifiedJavaType(IntrospectedTable introspectedTable) {
        List<IntrospectedColumn> primaryKeyColumns = introspectedTable.getPrimaryKeyColumns();
        Preconditions.checkArgument(Objects.nonNull(primaryKeyColumns) && primaryKeyColumns.size() == 1, "仅支持单一主键primaryKeyColumns的size必须为1。");
        IntrospectedColumn introspectedColumn = primaryKeyColumns.get(0);
        return introspectedColumn.getFullyQualifiedJavaType();
    }

}
